//
//  SEGHAllDoorView.m
//  SEGUhomeIntelligentHardware
//
//  Created by MOON FLOWER on 2018/7/5.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGHAllDoorView.h"
#import "SEGAllDoorCollectionViewLayout.h"
#import "SEGOpenDoorBaseAPI.h"
#import <SEGViewModel/SEGDoorListViewModel.h>

#define SEGDootCellHeight 130
#define SEGDoorListMarginTop 150.0

@interface SEGHAllDoorView () <UICollectionViewDataSource,UICollectionViewDelegate, SEGAllDoorCollectionViewLayoutProtocal>

@property (nonatomic, strong) UIButton *closeBt;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *problemBtn;
@property (nonatomic, strong) NSMutableArray<SEGNewMyDoorListModel *> *oldSpecialDoors; // 保存拖拽排序前的前八个门禁列表
@property (nonatomic, assign) BOOL needUpdateFlag; // 需要更新数据
@property (nonatomic, assign) BOOL isDrag; // 正在拖拽排序
@property (nonatomic, strong) UIView *noDataView;
@property (nonatomic, strong) UILabel *tipLabel;

@property (nonatomic, strong) SEGDoorListViewModel *doorListViewModel;

@end

@implementation SEGHAllDoorView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createUI];
    }
    return self;
}

- (void)createUI {
    [self addSubview:self.allDoorsView];
    CGFloat buttonViewHeight = 50.0;
    self.bottomView.frame=CGRectMake(0, LYScreenHeight()-buttonViewHeight-LYSafeAreaBottom(), LYScreenWidth(), buttonViewHeight+LYSafeAreaBottom());
    [self addSubview:self.bottomView];
    self.closeBt.frame = CGRectMake(0, 0, LYScreenWidth(), buttonViewHeight);
    [self.bottomView addSubview:self.closeBt];
    self.problemBtn.frame = CGRectMake(LYScreenWidth() - buttonViewHeight, 0, buttonViewHeight, buttonViewHeight);
    [self.bottomView addSubview:self.problemBtn];
    
    [self.allDoorsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(buttonViewHeight+LYSafeAreaBottom());
    }];
    
    [self.closeBt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.bottomView);
        make.width.height.mas_equalTo(30);
    }];
    
    [self.problemBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(self.bottomView);
        make.width.mas_equalTo(buttonViewHeight);
    }];
    
    self.tipLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [_allDoorsView addSubview:lable];
        lable.textColor = kColor_3;
        lable.font = kFont_13;
        lable.text = @"长按门禁按钮，拖拽调整排序";
        lable.textAlignment = NSTextAlignmentCenter;
        lable.numberOfLines = 0;
        lable;
    });
    
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.allDoorsView.mas_left);
        make.width.mas_equalTo(LYScreenWidth());
        make.top.mas_equalTo(-110);
        make.height.mas_equalTo(110);
    }];
    
    self.noDataView = ({
        UIView *nodataView = [[UIView alloc] init];
        nodataView.backgroundColor = kColor_W;
        [self addSubview:nodataView];
        UIImageView *tipImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_page")]];
        [nodataView addSubview:tipImageView];
        [tipImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(nodataView);
            make.centerY.equalTo(nodataView).offset(-10);
        }];
        
        UILabel* titleLabel = [[UILabel alloc] init];
        [titleLabel setText:KnoDoorsMesssage];
        [titleLabel setTextAlignment:NSTextAlignmentCenter];
        [titleLabel setFont:kFont_13];
        [titleLabel setTextColor:kColor_3];
        [nodataView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(tipImageView.mas_centerX);
            make.top.equalTo(tipImageView.mas_bottom).offset(20);
        }];
        nodataView.hidden = YES;
        nodataView;
    });
    
    [self.noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.allDoorsView);
    }];
}

// 监听暗黑切换
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    // 执行操作
    [self.closeBt setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_opendoor_close")] forState:UIControlStateNormal];
    [self.problemBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_open_door_setting")] forState:UIControlStateNormal];
}

#pragma mark==datasouce
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SEGDoorCollViewCell*cell=[collectionView dequeueReusableCellWithReuseIdentifier:[SEGDoorCollViewCell reusefer] forIndexPath:indexPath];
    SEGNewMyDoorListModel*model=self.dataSource[indexPath.row];
    cell.model=model;
    cell.index=indexPath;

    if (self.isDrag) {
        [cell addAnimation];
    } else {
         // 在停止拖拽的时候 移除cell动画
        [cell removeAnimation];
        cell.hidden = NO;
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SEGNewMyDoorListModel *model = self.dataSource[indexPath.row];
    if (self.itemBox) {
        self.itemBox(model);
    }
}

- (void)setDataSource:(NSArray<SEGNewMyDoorListModel *> *)dataSource {
    _dataSource = dataSource;

    CGFloat collectionHeight = floor(SEGDootCellHeight * ceil(dataSource.count*1.0/[SEGCommonConfig shared].newDoorDisplayCountOfRow));
    CGFloat leftHeight = LYScreenHeight() - kStatusbarHeight - LYSafeAreaBottom() - SEGDoorListMarginTop - 50;
    // 门禁列表不足一页的时候 列表除去顶部空白之后居中显示
    if (_dataSource.count > 0 && collectionHeight <= leftHeight) {
        _allDoorsView.scrollEnabled = NO;
        _allDoorsView.contentInset = UIEdgeInsetsMake((leftHeight - collectionHeight)/2.0 + SEGDoorListMarginTop, 0, 0, 0);
        [self layoutSubviews];
    } else {
        _allDoorsView.scrollEnabled = YES;
        _allDoorsView.contentInset = UIEdgeInsetsMake(SEGDoorListMarginTop, 0, 0, 0);
    }
    
    self.noDataView.hidden = _dataSource.count != 0;
    
    // 保存前八个门禁
    self.oldSpecialDoors = [[NSMutableArray alloc] init];
    [self.dataSource enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx < [SEGCommonConfig shared].newDoorSpecialNumber) {
            [self.oldSpecialDoors addObject:obj];
        } else {
            *stop = YES;
        }
    }];
    
    [_allDoorsView reloadData];
}

- (void)needUpdateData:(NSArray<SEGNewMyDoorListModel *> *)tempDataSource {
    if (self.isDrag) {
        self.needUpdateFlag = YES;
    } else {
        self.dataSource = tempDataSource;
        self.needUpdateFlag = NO;
    }
}

- (void)updateTipLabelText:(NSString *)text {
    self.tipLabel.text = text;
}

- (void)hideCloseButton {
    self.closeBt.hidden = YES;
}

#pragma mark==button Action
//关闭
-(void)closeActiond:(UIButton*)sender{
    sender.selected=!sender.selected;
    if (self.closeBox) {
        self.closeBox();
    }
    [self rotateCloseButton:sender.selected];
}

// 门禁答疑
- (void)problemBtnTap:(UIButton *)sender {
    if (self.problemBlock) {
        self.problemBlock();
    }
}

- (void)rotateCloseButton:(BOOL)isShow {
    CATransform3D start = CATransform3DMakeRotation(-M_PI_4, 0.001, 0.001, 1);
    CATransform3D end = CATransform3DIdentity;
    self.closeBt.imageView.layer.transform = isShow ? start : end;
    [UIView animateWithDuration:0.25 animations:^{
        self.closeBt.imageView.layer.transform = isShow ? end : start;
    }];
}


#pragma mark==视图
- (UICollectionView*)allDoorsView {
    if (!_allDoorsView) {
        SEGAllDoorCollectionViewLayout *layout = [[SEGAllDoorCollectionViewLayout alloc] init];
        layout.delegate = self;
        layout.footerReferenceSize = CGSizeMake(LYScreenWidth(), kScaleWidth*30);
        layout.minimumLineSpacing = 0.5;
        layout.minimumInteritemSpacing = 0.5;
        CGFloat cellWidth = floor((LYScreenWidth()-1)*1.0/[SEGCommonConfig shared].newDoorDisplayCountOfRow);
        layout.itemSize = CGSizeMake(cellWidth, SEGDootCellHeight);
        
        _allDoorsView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, LYSafeAreaTop()+30, LYScreenWidth(), LYScreenHeight()-50-LYSafeAreaBottom()-LYSafeAreaTop()-30) collectionViewLayout:layout];
        _allDoorsView.dataSource = self;
        _allDoorsView.delegate = self;
        _allDoorsView.backgroundColor = kColor_W;
        [_allDoorsView registerClass:[SEGDoorCollViewCell class] forCellWithReuseIdentifier:[SEGDoorCollViewCell reusefer]];
        if (@available(iOS 11.0, *)) {
            _allDoorsView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _allDoorsView;
}

- (UIButton *)closeBt {
    if (!_closeBt) {
        _closeBt =[UIButton buttonWithType:UIButtonTypeCustom];
        _closeBt.backgroundColor=kColor_W;
        [_closeBt setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_opendoor_close")] forState:UIControlStateNormal];
        [_closeBt addTarget:self action:@selector(closeActiond:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBt;
}

- (UIButton *)problemBtn {
    if (!_problemBtn) {
        _problemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _problemBtn.backgroundColor = [UIColor clearColor];
        [_problemBtn addTarget:self action:@selector(problemBtnTap:) forControlEvents:UIControlEventTouchUpInside];
        [_problemBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_open_door_setting")] forState:UIControlStateNormal];
    }
    return _problemBtn;
}

- (UIView*)bottomView {
    if (!_bottomView) {
        _bottomView = [UIView new];
        _bottomView.frame = CGRectZero;
        _bottomView.backgroundColor = kColor_W;
    }
    return _bottomView;
}

#pragma mark - SEGAllDoorCollectionViewLayoutProtocal

- (void)collectionViewDidBeginDrag {
    self.isDrag = YES;
}

- (NSArray *)collectionViewDataSourceArray:(UICollectionView *)collectionView {
    return [_dataSource copy];
}

- (void)collectionView:(UICollectionView *)collectionView didDragCellWithNewData:(NSArray *)newDataSource {
    _dataSource = [newDataSource copy];
}

- (void)collectionViewDidEndDragCell:(UICollectionView *)collectionView {
    // save data
    [self.doorListViewModel saveSortDoorList:self.dataSource];
    
    // 是否需要更新网络请求回来的数据
    self.isDrag = NO;
    if (self.needUpdateFlag) {
        self.dataSource = [self.doorListViewModel getLocalAllDoorList];
        self.needUpdateFlag = NO;
        return;
    }
    
    [self updateUI];
}

- (void)updateUI {
    NSMutableArray *newSpecialDoors = [[NSMutableArray alloc] init];
    [self.dataSource enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx < [SEGCommonConfig shared].newDoorSpecialNumber) {
            [newSpecialDoors addObject:obj];
        } else {
            *stop = YES;
        }
    }];
    NSMutableSet *oldSet = [[NSMutableSet alloc] initWithArray:self.oldSpecialDoors];
    NSMutableSet *newSet = [[NSMutableSet alloc] initWithArray:newSpecialDoors];
    
    if (![oldSet isSubsetOfSet:newSet]) {
        // oldSet和newSet的差集 = oldSet和newSet的并集 - 交集
        NSMutableSet *insertSet = [[NSMutableSet alloc] initWithArray:self.oldSpecialDoors];
        [insertSet intersectSet:newSet];
        [oldSet unionSet:newSet];
        [oldSet minusSet:insertSet];
       
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [oldSet enumerateObjectsUsingBlock:^(id  _Nonnull obj, BOOL * _Nonnull stop) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.dataSource indexOfObject:obj] inSection:0];
                SEGDoorCollViewCell *cell = (SEGDoorCollViewCell *)[self.allDoorsView cellForItemAtIndexPath:indexPath];
                [cell changeImageWithIndexPath:indexPath];
            }];
        });
    }
    
    self.oldSpecialDoors = newSpecialDoors;
}

#pragma mark - Getter

- (SEGDoorListViewModel *)doorListViewModel {
    if (!_doorListViewModel) {
        _doorListViewModel = [[SEGDoorListViewModel alloc] init];
    }
    return _doorListViewModel;
}

@end
